<template>
  <a-drawer title="角色的菜单与操作权限授权" :width="1000" :bodyStyle="{ padding: 0,marginBottom:'60px' }" :visible="visible" @close="close" destroyOnClose>
    <a-skeleton active :paragraph="{ rows: 16 }" :loading="loading">
      <a-table v-if="dataSource.length > 0" rowKey="id" size="middle" :columns="columns" :dataSource="treeData" :pagination="false" :row-selection="rowSelection" :indent-size="8"
        default-expand-all-rows>
        <template slot="auths" slot-scope="auths,record">
          <template v-if="Array.isArray(auths) && auths.length > 0">
            <a-checkbox-group :name="record.id" :disabled="!(roleMenus.includes(record.id))" :options="handleOptions(auths)" :default-value="handleDefaultValue(auths)" />
          </template>
        </template>
      </a-table>
      <a-empty v-else />

      <div class="sjht-drawer-footer">
        <a-button @click="close">关闭</a-button>
        <a-button type="primary" :loading="confirmLoading" @click.stop="onSubmit">确定授权</a-button>
      </div>
    </a-skeleton>
  </a-drawer>
</template>
<script>
import { intersection, pull, flattenDeep } from 'lodash' //intersection:交集,pull:数组删除,flattenDeep:递归为一维数组
import { listToTree } from '@/utils/common'
import { GetRoleMenuAndRoleMenuAuth, SaveMenuAndMenuAuth } from '@/api/manage/role'
import { Skeleton, Empty } from 'ant-design-vue'
export default {
  name: 'SjhtAuthTree', //角色的菜单与操作权限授权
  components: {
    [Skeleton.name]: Skeleton,
    [Empty.name]: Empty
  },
  data() {
    return {
      visible: false, //是否显示
      loading: false, //是否加载
      confirmLoading: false, //确认加载
      roleId: null, //角色ID
      dataSource: [],
      columns: [
        { title: '菜单名称', width: 200, dataIndex: 'title' },
        { title: '操作权限', dataIndex: 'auths', scopedSlots: { customRender: 'auths' } }
      ],
      roleMenus: [], //角色菜单-选择数组
      roleMenuAuths: [] //角色菜单操作权限-选择数组
    }
  },
  methods: {
    show(roleId) {
      this.visible = true
      if (this.loading) return
      this.loading = true // 加载数据
      GetRoleMenuAndRoleMenuAuth(roleId)
        .then(res => {
          this.dataSource = res.menu
          this.roleId = res.auth.roleId
          this.roleMenus = res.auth.roleMenus
          this.roleMenuAuths = res.auth.roleMenuAuths
        })
        .catch(err => {
          this.dataSource = []
          this.$message.error(err)
        })
        .finally(() => {
          this.loading = false
        })
    },
    close() {
      this.visible = false
    },
    onSubmit() {
      const { roleId, roleMenus, roleMenuAuths, dataSource, $message } = this
      if (roleMenus.length <= 0) {
        $message.error('没有选择任何菜单')
        return
      }
      //没有选择父级菜单列表
      const selectedRow = dataSource.filter(f => f.pid && roleMenus.includes(f.id) && !roleMenus.includes(f.pid))
      if (selectedRow.length > 0) {
        $message.error('选择子菜单要求必须选择父级菜单')
        return
      }

      this.confirmLoading = true
      //获取已经选中菜单的包括有操作权限的列表
      const authslist = dataSource.filter(f => roleMenus.includes(f.id) && Array.isArray(f.auths) && f.auths.length > 0)
      const authArr = flattenDeep(authslist.map(m => m.auths.map(a => a.id))) //将操作权限id展开数组
      const data = {
        roleId,
        roleMenus,
        roleMenuAuths: intersection(authArr, roleMenuAuths) //过滤选中的操作权限（取交集）
      }

      SaveMenuAndMenuAuth(data)
        .then(res => {
          if (res) {
            $message.success('授权成功')
            this.close()
          } else $message.error('授权失败')
        })
        .catch(err => {
          $message.error(err)
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    //处理选项
    handleOptions(auths) {
      return auths.map(m => ({
        value: m.id,
        label: m.name,
        onChange: e => {
          if (e.target.checked) {
            this.roleMenuAuths.push(e.target.value) //添加
          } else {
            pull(this.roleMenuAuths, e.target.value) //删除
          }
        }
      }))
    },
    //处理默认值
    handleDefaultValue(auths) {
      //取交集
      return intersection(
        this.roleMenuAuths,
        auths.map(m => m.id)
      )
    }
  },
  computed: {
    treeData: function () {
      return listToTree(this.dataSource)
    },
    rowSelection: function () {
      return {
        columnWidth: 35, //列表选择框宽度
        selectedRowKeys: this.roleMenus,
        onChange: keys => {
          this.roleMenus = keys
        }
      }
    }
  }
}
</script>